package com.heima.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Semaphore;

/**
 * @author 陈辉
 * @data 2023 15:33
 */
@RestController
public class ConcurrentController {

    @Autowired
    private Semaphore semaphore;

    //需求：当前业务操作，同一时刻只允许2个人操作
    @GetMapping("con")
    public String con(){
        try {
            //尝试获得锁
            semaphore.acquire();

            System.out.println(Thread.currentThread().getName()+"进来了...");
            Thread.sleep(100);      //模拟业务操作耗时
            System.out.println(Thread.currentThread().getName()+"出去了...");

            //释放锁
            semaphore.release();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "ok";
    }
}
